const { default: axios } = require("axios");
const crypto = require('crypto');
const dayjs = require("dayjs");
const xml2js = require('xml2js');

module.exports = {
	/**
	 * 生成订单号
	 * @param {Number} len 长度
	 */
	generateOrderNumber(len = 20) {
		const time = dayjs().format('YYYYMMDDHHmmss');
		const random = this.randomNumber(len - time.length);
		return time + random;
	},
	/**
	 * 生成随机数字
	 * @param {*} len 
	 */
	randomNumber(len) {
		len = len || 6;
		let nums = '';
		for (let i = 0; i < len; i++) {
			nums += Math.floor(Math.random() * 10);
		}
		return nums;
	},
	checkCode(code) {
		return /^\d{6}$/.test(code);
	},
	// 生成随机字符串
	randomString(len) {
		len = len || 32;
		const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		const maxPos = $chars.length;
		let pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	},
	success(data) {
		return {
			code: 0,
			data,
			message: 'success'
		}
	},
	/**
	 * 请求封装
	 * @param {String} url    请求地址
	 * @param {Object} data   请求参数
	 * @param {String} method 请求方式
	 * @returns 
	 */
	request(url, data, method = 'GET', headers = {}) {
		return new Promise((resolve, reject) => {
			axios({
				url,
				data: method === 'POST' ? data : null,
				method,
				params: method === 'GET' ? data : null,
				headers
			}).then(res => {
				resolve(res.data);
			}).catch(err => {
				reject(err);
			})
		})
	},
	/**
	 * 请求封装 object
	 * @param {import("axios").AxiosRequestConfig} obj
	 */
	requestObj(obj) {
		return new Promise((resolve, reject) => {
			axios(obj).then(res => {
				resolve(res.data);
			}).catch(err => {
				reject(err);
			})
		})
	},
	/**
	 * 密码加盐 256 加密
	 */
	signPass(pass) {
		const secret = '123456';
		const hash = crypto.createHmac('sha256', secret)
			.update(pass)
			.digest('hex');
		return hash;
	},
	/**
	 * 验证手机号码
	 */
	checkPhone(phone) {
		return /^1[3-9]\d{9}$/.test(phone);
	},
	/**
	 * 过滤数据
	 */
	filterData(data, allowFields) {
		const newData = {}
		for (let key in data) {
			if (allowFields.includes(key)) {
				newData[key] = data[key]
			}
		}
		return newData
	},
	/**
	 * 解析xml
	 * @param {*} xml 
	 * @returns 
	 */
	parseXML(xml) {
		return new Promise((resolve, reject) => {
			xml2js.parseString(xml, (err, result) => {
				if (err) {
					reject(err);
				} else {
					// xml 数据不能是数组
					const data = result.xml;
					const newData = {};
					for (let key in data) {
						newData[key] = data[key][0];
					}
					resolve(newData);
				}
			});
		});
	},
	/**
	 * 凯撒加密
	 * @param {*} str 
	 * @param {*} code 
	 * @param {*} type 
	 * @returns 
	 */
	caesar(str, code = 4, type = 0) {
		let newStr = '';
		for (let i = 0; i < str.length; i++) {
			let charCode = str.charCodeAt(i);
			if (type === 0) {
				charCode += code;
			} else {
				charCode -= code;
			}
			newStr += String.fromCharCode(charCode);
		}
		return newStr;
	},
}